<?php
/**
 * DESC: 商品模块
 * 作者:晨光
 * EMAIL:461718846@qq.com
 * DATE:2020/5/16
 */

namespace app\admin\controller;


use app\common\controller\AdminUserBase;
use app\common\controller\Plugin;
use app\common\model\GoodsCate;
use app\common\model\GoodsCateRelated;
use app\common\model\GoodsFormat;
use app\common\model\GoodsFormatName;
use app\common\model\GoodsFormatValue;
use think\Db;
use think\facade\Request;
use think\Validate;

class Goods extends AdminUserBase
{
    /**
     * 商品分类
     */
    public function goods_cate(){
        if (Request::isAjax()){
            $data = GoodsCate::order('sort asc')->append(['open'])->select();
            $this->result($data);
        }
        return view('cate');
    }
    public function goods_cate_tree(){
        $data = GoodsCate::order('sort asc')->select()->toArray();
        $this->result(array2tree($data));
    }
    public function goods_cate_save(){
        $param = input();

        $model = new GoodsCate();
        if (empty($param['id'])){
            $res = $model->allowField(true)->isUpdate(false)->save($param);
            saveAdminLog("添加商品分类");
        }else{
            $res = $model->allowField(true)->isUpdate(true)->save($param);
            saveAdminLog("编辑商品分类");
        }

        if ($res !== false){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function goods_cate_del(){
        $id = input('id');
//        判断当前节点下有没有子节点
        $ziNum = Db::name('GoodsCate')->where('pid',$id)->count();
        if ($ziNum > 0){
            $this->error('当前节点下有子分类无法删除，请先删除子分类');
        }
        $res = Db::name('GoodsCate')->delete($id);
        if ($res !== false){
            saveAdminLog("删除商品分类");
            $this->success();
        }else{
            $this->error();
        }
    }
    /**
     * 商品分类
     */

    /**
     * 商品列表
     */
    public function goods(){
        if (Request::isAjax()){
            $param = input();
            $where = [];
            $hasWhere = [];
            if (!empty($param['title'])){
                $where[] = ['title','like','%'.$param['title'].'%'];
            }
            if (!empty($param['article_cate_id'])){
                $hasWhere[] = ['article_cate_id','in',$param['article_cate_id']];
            }
            if (!empty($param['top'])){
                $where[] = ['top','=',$param['top']];
            }
            if (!empty($param['show'])){
                $where[] = ['show','=',$param['show']];
            }
            $data = \app\common\model\Goods::hasWhere('cateRelated',$hasWhere)->where($where)->order('sort desc')->paginate($param['limit']);
            $data = $data->toArray();
            $this->result($data['data'],$data['total']);
        }
        return view('goods/goods/index');
    }
    public function form(){
        $id = input('id');
//        规格名
        $formatName = GoodsFormatName::getList();
        $this->assign('formatName',$formatName);
//        查询商品信息
        $data = \app\common\model\Goods::get($id);
        if (!empty($data)){
            $data['cate_id'] = $data->cateRelated()->column('goods_cate_id');
            $data['cate_id'] = json_encode($data['cate_id']);
            $data['format'] = $data->goodsFormat()->select();
        }
        $this->assign('data',$data);

        return view('goods/goods/form');
    }
    public function goods_save(){
        $param = input();

        Db::startTrans();
        try {
            if (!isset($param['format'])){
                abort(1,'必须添加一个规格');
            }
            $goodsModel = new \app\common\model\Goods();
            if (empty($param['id'])){
                unset($param['id']);
                $shop_id = explode(',',$param['shop_id']);
                foreach ($shop_id as $ks=>$vs){
                    $shopInfo = Db::name('shop')->where('id',$vs)->field('lng,lat,province,city,area')->find();
                    $param['shop_id'] = $vs;
                    $param['lng'] = $shopInfo['lng'];
                    $param['lat'] = $shopInfo['lat'];
                    $param['province'] = $shopInfo['province'];
                    $param['city'] = $shopInfo['city'];
                    $param['area'] = $shopInfo['area'];

                    $goodsModel->allowField(true)->isUpdate(false)->save($param);
                    if (isset($param['goods_cate_id']) && is_string($param['goods_cate_id'])){
                        $goods_cate_id = explode(',',$param['goods_cate_id']);
                        if (is_array($goods_cate_id)){
                            $cate_ids = [];
                            foreach ($goods_cate_id as $k=>$v){
                                $cate_ids[] = [
                                    'goods_cate_id'=>$v
                                ];
                            }
                            $goodsModel->cateRelated()->saveAll($cate_ids);
                        }
                    }else{
                        abort(1,'未选择商品分类');
                    }
//                商品规格
                    if (isset($param['format']) && !empty($param['format'])){
                        $formatSaveData = [];
                        $format = $param['format'];
                        foreach ($format['sku'] as $kf=>$vf){
                            $formatSaveData[] = [
                                'sku'=>implode(',',$vf),
                                'img'=>$format['img'][$kf],
                                'price'=>$format['price'][$kf],
                                'cost_price'=>$format['cost_price'][$kf],
                                'original_price'=>$format['original_price'][$kf],
                                'stock'=>$format['stock'][$kf],
                                'weight'=>$format['weight'][$kf],
                                'volume'=>$format['volume'][$kf],
                            ];
                        }
                        $goodsModel->goodsFormat()->saveAll($formatSaveData);
                    }
                }
                saveAdminLog("添加商品");
            }else{
                $shopInfo = Db::name('shop')->where('id',$param['shop_id'])->field('lng,lat,province,city,area')->find();
                $param['lng'] = $shopInfo['lng'];
                $param['lat'] = $shopInfo['lat'];
                $param['province'] = $shopInfo['province'];
                $param['city'] = $shopInfo['city'];
                $param['area'] = $shopInfo['area'];

                $goodsModel->allowField(true)->isUpdate(true)->save($param);
//                编辑的使用，使用中间件模型
                if (isset($param['goods_cate_id']) && is_string($param['goods_cate_id'])){
                    $goods_cate_id = explode(',',$param['goods_cate_id']);
//                    查询编辑之前的内容分类
                    $oldCategoryIds        = $goodsModel->cate()->column('goods_cate_id');
//                    查出来相同的内容分类
                    $sameCategoryIds       = array_intersect($goods_cate_id, $oldCategoryIds);
//                    查询需要删除的内容分类
                    $needDeleteCategoryIds = array_diff($oldCategoryIds, $sameCategoryIds);
//                    查询需要插入的内容分类
                    $newCategoryIds        = array_diff($goods_cate_id, $sameCategoryIds);

//                    中间模型自动删除需要删除的分类
                    if (!empty($needDeleteCategoryIds)) {
                        $goodsModel->cate()->detach($needDeleteCategoryIds);
                    }

//                    中间模型自动添加内容分类
                    if (!empty($newCategoryIds)) {
                        $goodsModel->cate()->attach(array_values($newCategoryIds));
                    }
                }

//                商品规格
                if (isset($param['format']) && !empty($param['format'])){
                    $formatSaveData = [];
                    $format = $param['format'];
                    if (isset($format['id']) && !empty($format['id'])){
//                        编辑规格
                        foreach ($format['sku'] as $kf=>$vf){
                            $formatSaveData[] = [
                                'sku'=>$vf,
                                'img'=>$format['img'][$kf],
                                'price'=>$format['price'][$kf],
                                'cost_price'=>$format['cost_price'][$kf],
                                'original_price'=>$format['original_price'][$kf],
                                'stock'=>$format['stock'][$kf],
                                'weight'=>$format['weight'][$kf],
                                'volume'=>$format['volume'][$kf],
                                'id'=>$format['id'][$kf],
                            ];
                        }
                    }else{
//                        先把原来的给删除
                        Db::name('goodsFormat')->where('goods_id',$param['id'])->delete();
//                        新建规格
                        foreach ($format['sku'] as $kf=>$vf){
                            $formatSaveData[] = [
                                'sku'=>implode(',',$vf),
                                'img'=>$format['img'][$kf],
                                'price'=>$format['price'][$kf],
                                'cost_price'=>$format['cost_price'][$kf],
                                'original_price'=>$format['original_price'][$kf],
                                'stock'=>$format['stock'][$kf],
                                'weight'=>$format['weight'][$kf],
                                'volume'=>$format['volume'][$kf],
                            ];
                        }
                    }
                    $goodsModel->goodsFormat()->saveAll($formatSaveData);
                }
                saveAdminLog("编辑商品内容");
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }
    public function goods_edit_save(){
        $res = \app\common\model\Goods::goods_edit_save(input());
        if ($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function getFormatValue(){
        $format_name_id = input('goods_format_name_id');
        $data = GoodsFormatValue::where('goods_format_name_id','=',$format_name_id)->select();
        return $this->result($data);
    }
    public function shop_list(){
        $data = \app\common\model\Shop::select();
        return $this->result($data);
    }
    public function goods_del(){
        $id = input('id');
        if (empty($id)){
            $id = input('ids');
        }
//        删除对应商品的规格
        GoodsFormat::where('goods_id','in',$id)->delete();
//        删除商品分类对应关系
        GoodsCateRelated::where('goods_id','in',$id)->delete();
        $res = \app\common\model\Goods::destroy($id);
        if ($res !== false){
            saveAdminLog("软删除内容");
            $this->success();
        }else{
            $this->error();
        }
    }
    /**
     * 商品列表
     */

    /**
     * 规格信息
     */
    public function format_name(){
        if (Request::isAjax()){
            $params = input();
            $where = [];
            if (!empty($params['keywords'])){
                $where[] = ['name','like','%'.$params['keywords'].'%'];
            }
            $data = GoodsFormatName::where($where)->select();
            $this->result($data);
        }
        return view('format');
    }
    public function format_name_save(){
        $param = input();
        //        验证
        $validate = Validate::make([
            'name|名称'=>'require|unique:GoodsFormatName',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }

        $model = new GoodsFormatName();

        if (empty($param['id'])){
            $param['admin_id'] = session('admin.id');
            $res = $model->allowField(true)->isUpdate(false)->save($param);
        }else{
            $res = $model->allowField(true)->isUpdate(true)->save($param,['id'=>$param['id']]);
        }

        if ($res !== false){
            $this->success('提交成功');
        }else{
            $this->error('提交失败');
        }
    }
    public function format_name_del(){
        $id = input('id');
//        检查是不是有子项
        $isZhi = Db::name('GoodsFormatValue')->where(['goods_format_name_id'=>$id])->count();
        if ($isZhi > 0){
            $this->error('当前规则名有对应的规格值，请先删除');
        }

        $res = GoodsFormatName::destroy($id);
        if ($res !== false){
            saveAdminLog("删除字典配置");
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    public function format_value(){
        if (Request::isAjax()){
            $param = input();
            $where = [];
            if (!empty($param['goods_format_name_id'])){
                $where[] = ['goods_format_name_id','=', $param['goods_format_name_id']];
            }
            if (!empty($param['item'])){
                $where[] = ['name','like','%'.$param['item'].'%'];
            }
            $data = GoodsFormatValue::where($where)->paginate($param['limit']);

            $data = $data->toArray();
            $this->result($data['data'],$data['total'],'0',$param['goods_format_name_id']);
        }
        return view('format');
    }
    public function format_value_save(){
        $param = input();

        $model = new GoodsFormatValue();

        if (empty($param['id'])){
            $param['admin_id'] = session('admin.id');
            $res = $model->allowField(true)->isUpdate(false)->save($param);
            saveAdminLog("添加规格值");
        }else{
            $res = $model->allowField(true)->isUpdate(true)->save($param,['id'=>$param['id']]);
            saveAdminLog("编辑规格值");
        }

        if ($res !== false){
            $this->success('提交成功');
        }else{
            $this->error('提交失败');
        }
    }
    public function format_value_del(){
        $id = input('id');
        if (empty($id)){
            $id = input('ids');
        }
        $res = GoodsFormatValue::destroy($id);
        if ($res !== false){
            saveAdminLog("删除规格值");
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    /**
     * 规格信息
     */
}
